package com.example.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter extends org.springframework.web.filter.CharacterEncodingFilter {

	private String encoding;
	
	private boolean forceEncoding;
	
	private Map<String, String> specialEncoding = new HashMap<String, String>();

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

	public void setSpecial(String special) {
		String[] specials = special.split("\\,");
		for(String value : specials) {
			String[] values = value.split("\\_");
			specialEncoding.put(values[0], values[1]);
		}
	}

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		HttpServletRequest req = (HttpServletRequest)request;
		String uri = req.getRequestURI();
		boolean isSet = false;
		for(Entry<String, String> entry : specialEncoding.entrySet()) {
			if(uri.contains(entry.getKey())) {
				request.setCharacterEncoding(entry.getValue());
				isSet = true;
				break;
			}
		}
		if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			if(!isSet) {
				request.setCharacterEncoding(this.encoding);
			}
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}
}